package com.airline.service;

import com.airline.entity.Booking;
import com.airline.entity.Flight;
import com.airline.entity.User;
import com.airline.repository.BookingRepository;
import com.airline.repository.FlightRepository;
import com.airline.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class BookingService {
    private final BookingRepository bookingRepository;
    private final UserRepository userRepository;
    private final FlightRepository flightRepository;

    // 创建预订
    public Booking createBooking(Long userId, Long flightId, String passengerName, String seatClass) {
        // 查找用户
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        // 查找航班
        Flight flight = flightRepository.findById(flightId)
                .orElseThrow(() -> new RuntimeException("航班不存在"));

        // 检查座位是否可用
        if (flight.getAvailableSeats() <= 0) {
            throw new RuntimeException("航班已满，无法预订");
        }

        // 计算价格
        BigDecimal price = calculatePrice(flight, seatClass);

        // 创建预订
        Booking booking = new Booking();
        booking.setUser(user);
        booking.setFlight(flight);
        booking.setPassengerName(passengerName);
        booking.setSeatClass(seatClass);
        booking.setPrice(price);
        booking.setBookingTime(LocalDateTime.now());
        booking.setStatus("CONFIRMED");

        // 减少可用座位数
        flight.setAvailableSeats(flight.getAvailableSeats() - 1);
        flightRepository.save(flight);

        return bookingRepository.save(booking);
    }

    // 获取用户的所有预订
    public List<Booking> getUserBookings(Long userId) {
        return bookingRepository.findByUserId(userId);
    }

    // 根据ID获取预订
    public Optional<Booking> getBookingById(Long id) {
        return bookingRepository.findById(id);
    }

    // 获取所有预订
    public List<Booking> getAllBookings() {
        return bookingRepository.findAll();
    }

    // 更新预订状态（带权限验证）
    public Booking updateBookingStatus(Long bookingId, String status, Long currentUserId) {
        Optional<Booking> bookingOpt = bookingRepository.findById(bookingId);
        if (bookingOpt.isPresent()) {
            Booking booking = bookingOpt.get();

            // 添加权限验证：只能操作自己的预订
            if (!booking.getUser().getId().equals(currentUserId)) {
                throw new RuntimeException("无权操作此预订：该预订不属于当前用户");
            }

            // 验证状态值
            if (!isValidStatus(status)) {
                throw new RuntimeException("无效的状态值: " + status + "。有效状态: PENDING, CONFIRMED, CANCELLED, CHECKED_IN, BOARDED, COMPLETED");
            }

            booking.setStatus(status);
            return bookingRepository.save(booking);
        } else {
            throw new RuntimeException("预订不存在，ID: " + bookingId);
        }
    }

    // 计算价格
    private BigDecimal calculatePrice(Flight flight, String seatClass) {
        if ("BUSINESS".equalsIgnoreCase(seatClass)) {
            return flight.getBusinessPrice();
        } else {
            return flight.getEconomyPrice();
        }
    }

    // 验证状态值是否有效
    private boolean isValidStatus(String status) {
        List<String> validStatuses = Arrays.asList(
                "PENDING", "CONFIRMED", "CANCELLED", "CANCELED",
                "CHECKED_IN", "BOARDED", "COMPLETED", "NO_SHOW"
        );
        return validStatuses.contains(status.toUpperCase());
    }
}